package com.demo;

import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.*;
import java.sql.*;
@WebServlet("/BookQueryServlet")
public class BookQueryServlet extends HttpServlet {
private static final long serialVersionUID = 1L; 
Connection dbconn;
BookBean book = new BookBean(); 
public void init() {
			String driver = "com.mysql.cj.jdbc.Driver";
			String dburl = "jdbc:mysql://localhost:3306/postgres";
			String username = "root";
			String password = "123456";
try{

		Class.forName(driver); 
		dbconn = DriverManager.getConnection(dburl,username,password);
	}catch(ClassNotFoundException cfe){
			log("Exception:"+cfe);
	}catch(SQLException sqle){
		log("Exception:"+sqle);
	}
 }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	this.doPost(request, response);
}
public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException,IOException{
		String bookid = request.getParameter("bookid");
	try{
		String sql="SELECT * FROM books WHERE bookid=?";
		PreparedStatement pstmt = dbconn.prepareStatement(sql);
		pstmt.setString(1,bookid);
		ResultSet rst = pstmt.executeQuery();
		if(rst.next()){
			book.setBookid(rst.getString("bookid"));
			book.setTitle(rst.getString("title"));
			book.setAuthor(rst.getString("author"));
			book.setPrice(rst.getFloat("price"));
			book.setPublisher(rst.getString("publisher"));
			request.getSession().setAttribute("book", book);
			RequestDispatcher view =
					request.getRequestDispatcher("/displayBook.jsp");
			view.forward(request, response);
		}else{
			RequestDispatcher view =request.getRequestDispatcher("/error.jsp");
			view.forward(request, response);
		}
	}catch(SQLException e){
		e.printStackTrace();
	}
	}
public void destroy(){
		try {
			dbconn.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
}
	


